<template>
  <div v-loading="infoLoading">

    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-dialog
        :title="jzrDialogTitle"
        :visible.sync="jzrDialogVisible"
        width="98%"
        top="20px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
      >
        <el-form ref="jzrForm" :model="jzrForm" class="form-container" label-width="200px">
          <el-form-item label="姓名" prop="xm">
            <el-input v-model="jzrForm.xm" style="width:200px;" />
          </el-form-item>
          <el-form-item label="身份证号" prop="sfzh">
            <el-input v-model="jzrForm.sfzh" style="width:300px;" />
          </el-form-item>
          <el-form-item label="电话" prop="dh">
            <el-input v-model="jzrForm.dh" style="width:200px;" />
          </el-form-item>
          <el-form-item label="户籍" prop="hj">
            <el-input v-model="jzrForm.hj" style="width:200px;" />
          </el-form-item>
          <el-form-item label="现住址" prop="xzz">
            <el-input v-model="jzrForm.xzz" style="width:300px;" />
          </el-form-item>
          <el-form-item label="微信名" prop="wxm">
            <el-input v-model="jzrForm.wxm" style="width:200px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveJzr">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <h2>集资参与人代表基本信息</h2>
      <el-button v-if="!subReadOnly" class="filter-item" type="success" icon="el-icon-edit" style="margin:0 0 10px" @click="addJzr">
        新增集资参与人代表
      </el-button>
      <el-table
        :data="xfrList"
        border
        fit
        highlight-current-row
        style="width: 100%;margin-bottom:20px;"
        @sort-change="sortChange"
      >

        <el-table-column
          align="center"
          type="index"
          label="序号"
          width="50px"
          :index="indexMethod"
        />

        <el-table-column width="100px" prop="xm" align="center" label="姓名" />
        <el-table-column width="200px" prop="sfzh" align="center" label="身份证号" />
        <el-table-column width="200px" prop="dh" align="center" label="电话" />
        <el-table-column width="200px" prop="hj" align="center" label="户籍" />
        <el-table-column min-width="200px" prop="xzz" align="center" label="现住址" />
        <el-table-column width="200px" prop="wxm" align="center" label="微信名" />
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <!-- <el-button v-if="!subReadOnly" size="small" type="primary" icon="el-icon-edit" @click="editJzr(scope.row.sfzh)">修改</el-button> -->
            <el-popconfirm v-if="!subReadOnly" title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteJzr(scope.$index)">
              <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="200px">
        <el-form-item label="信访时间" prop="xfsj">
          <el-date-picker v-if="!subReadOnly" v-model="postForm.xfsj" style="width:200px" value-format="yyyy-MM-dd" />
          <span v-else>{{ postForm.xfsj }}</span>
        </el-form-item>
        <el-form-item label="接访单位" prop="zrdw">
          <el-input v-if="!subReadOnly" v-model="postForm.zrdw" style="width:400px" />
          <span v-else>{{ postForm.zrdw }}</span>
        </el-form-item>
        <el-form-item label="接访人" prop="zrld">
          <el-input v-if="!subReadOnly" v-model="postForm.zrld" style="width:200px" />
          <span v-else>{{ postForm.zrld }}</span>
        </el-form-item>
        <!-- <el-form-item label="责任领导电话" prop="zrlddh">
          <el-input v-if="!subReadOnly" v-model="postForm.zrlddh" style="width:200px" />
          <span v-else>{{ postForm.zrlddh }}</span>
        </el-form-item> -->
        <!-- <el-form-item label="具体责任人" prop="jtzrr">
          <el-input v-if="!subReadOnly" v-model="postForm.jtzrr" style="width:200px" />
          <span v-else>{{ postForm.jtzrr }}</span>
        </el-form-item> -->
        <el-form-item label="责任人电话" prop="zrrdh">
          <el-input v-if="!subReadOnly" v-model="postForm.zrrdh" style="width:200px" />
          <span v-else>{{ postForm.zrrdh }}</span>
        </el-form-item>
        <!-- <el-form-item label="信访类别" prop="xflb">
          <el-select v-if="!subReadOnly" v-model="postForm.xflb" placeholder="请选择" style="width:200px;">
            <el-option
              v-for="item in xflbList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span v-else>{{ xflbList&&xflbList.find(item=>item.value===postForm.xflb)?xflbList.find(item=>item.value===postForm.xflb).label:'' }}</span>
        </el-form-item> -->
        <!-- <el-form-item label="进京赴省到市来区访情况" prop="jjfsdslqfqk">
          <el-input v-if="!subReadOnly" v-model="postForm.jjfsdslqfqk" type="textarea" style="width:800px" />
          <span v-else>{{ postForm.jjfsdslqfqk }}</span>
        </el-form-item> -->
        <el-form-item label="主要诉求" prop="zysq">
          <el-input v-if="!subReadOnly" v-model="postForm.zysq" type="textarea" style="width:800px" />
          <span v-else>{{ postForm.zysq }}</span>
        </el-form-item>
        <el-form-item label="答复内容" prop="dfnr">
          <el-input v-if="!subReadOnly" v-model="postForm.dfnr" type="textarea" style="width:800px" />
          <span v-else>{{ postForm.dfnr }}</span>
        </el-form-item>
        <div>
          <upload-files v-if="!infoLoading" :id="postForm.id" :cfajbh="cfajbh" :read-only="subReadOnly" table="bus_ww" :timestamp="subtimestamp" @updateFj="updateFj" />
        </div>
        <el-form-item style="margin:10px 0">
          <el-button v-if="!subReadOnly" type="success" :loading="loading" @click="submitForm(1)">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div v-if="showDuban">
      <supervise v-if="showSupervise()" business-table="bus_ww" :cfajbh="cfajbh" :timestamp="timestamp" />
    </div>
    <h2>详细信息</h2>
    <el-button v-if="unitName==='政法委'&&roleName==='录入'" class="filter-item" type="success" icon="el-icon-edit" style="margin:0 0 10px" @click="addnew">
      新增维稳工作记录
    </el-button>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >

      <el-table-column
        align="center"
        type="index"
        label="序号"
        width="50px"
        :index="indexMethod"
      />

      <el-table-column width="120px" prop="xfsj" align="center" label="时间" sortable="custom" />
      <el-table-column min-width="200px" prop="zysq" align="center" label="主要诉求" show-overflow-tooltip />
      <!-- <el-table-column width="200px" prop="xflb" align="center" label="信访类别" sortable="custom">
        <template slot-scope="scope">
          {{ xflbList&&xflbList.find(item=>item.value===scope.row.xflb)?xflbList.find(item=>item.value===scope.row.xflb).label:'' }}
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-search" @click="detail(scope.row.id)">详情</el-button>
          <el-button v-if="canEdit(scope.row.gazt)" size="small" type="primary" icon="el-icon-edit" @click="edit(scope.row.id)">修改</el-button>
          <el-popconfirm v-if="canEdit(scope.row.gazt)" title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.id)">
            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getData" />

  </div>
</template>

<script>

import uploadFiles from './uploadfilesId.vue'
import supervise from './supervise.vue'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const defaultForm = {
  xfsj: '',
  zrdw: '',
  zrld: '',
  zrlddh: '',
  jtzrr: '',
  zrrdh: '',
  xflb: '',
  jjfsdslqfqk: '',
  zysq: '',
  dfnr: '',
  id: null
}
const defaultFileForm = {
  fileid: 0,
  remark: ''
}
const defaultJzrForm = {
  xm: '',
  sfzh: '',
  dh: '',
  hj: '',
  xzz: '',
  wxm: ''
}
export default {
  name: 'ArticleDetail',
  components: { Pagination, uploadFiles, supervise },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    showDuban: {
      type: Boolean,
      default: false
    },
    cfajbh: {
      type: String,
      default: ''
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    },
    step: {
      type: String,
      default: ''
    }
  },
  data() {
    // const validateRequire = (rule, value, callback) => {
    //   if (!value || value === '') {
    //     // this.$message({
    //     //   message: '请将表单填写完整',
    //     //   type: 'error'
    //     // })
    //     callback(new Error('必填项'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      xfrList: [],
      jzrForm: Object.assign({}, defaultJzrForm),
      xflbList: [{ value: 1, label: '来区' }, { value: 2, label: '到市' }, { value: 3, label: '赴省' }, { value: 4, label: '进京' }],
      xyrAll: [],
      subReadOnly: false,
      subtimestamp: 0,
      dialogVisible: false,
      dialogtitle: '',
      list: [],
      total: 0,
      Sortkey: '',
      Isace: '',
      listQuery: {
        page: 1,
        limit: 10
      },
      hist: {},
      auditFlag: false,
      ajh: '',
      ajmc: '',
      fjloading: false,
      fjindex: -1,
      fileList: [],
      fjlList: [],
      fjList: [],
      jzrDialogVisible: false,
      jzrDialogTitle: '新增',
      myid: 0,
      unitName: '',
      roleName: '',
      deptName: '',
      realName: '',
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      filePostForm: Object.assign({}, defaultFileForm),
      loading: false,
      deptOption: [],
      userOption: [],
      processUserOption: [],
      priorityOption: [],
      classCodeOption: [],
      flowTypeOption: [],
      rules: {
      },
      processListLoading: false,
      processList: [],
      processNow: {},
      mystep: ''
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs['postForm']) {
          this.$refs['postForm'].resetFields()
        }
        this.mystep = this.step
        this.getXyrAll()
        this.getData()
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    const userinfo = JSON.parse(localStorage.getItem('user'))
    this.unitName = userinfo.unitName
    this.roleName = userinfo.roleName
    // this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
  },
  methods: {
    deleteJzr(index) {
      this.xfrList.splice(index, 1)
      // this.xfrList = this.xfrList.filter(item => item.sfzh !== sfzh)
    },
    editJzr(sfzh) {
      this.jzrDialogVisible = true
      this.jzrDialogTitle = '修改集资人'
      this.jzrForm = this.xfrList.find(item => item.sfzh === sfzh)
    },
    addJzr() {
      this.jzrDialogVisible = true
      this.jzrDialogTitle = '新增集资人'
      this.jzrForm = Object.assign({}, defaultJzrForm)
    },
    saveJzr() {
      // if (this.jzrForm.sfzh) {
      this.xfrList.push({ xm: this.jzrForm.xm, sfzh: this.jzrForm.sfzh, dh: this.jzrForm.dh, hj: this.jzrForm.hj, xzz: this.jzrForm.xzz, wxm: this.jzrForm.wxm })
      this.jzrDialogVisible = false
      // } else {
      //   this.$message({
      //     message: '请填写身份证号',
      //     type: 'error'
      //   })
      // }
    },
    deleteData(id) {
      this.$http
        .post('/api/busWw/remove', { ids: [id] })
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getXyrAll()
            this.getData()
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getXyrAll() {
      this.infoLoading = true
      if (this.infoid) {
        this.$http
          .get('/api/ga/getGaById?&id=' + this.infoid)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.xyrAll = []
              this.xyrlist = []
              const gkqkList = response.data.result.gkqkList
              const sfzhs = Array.from(new Set(response.data.result.gkqkList.map(item => item.sfzh))) // 身份证号去重
              sfzhs.forEach(item => {
                const person = gkqkList.filter(it => it.sfzh === item) // 过滤出这个身份证号的所有人
                if (person.find(it => it.ysscqsId)) {
                  this.xyrAll.push({ id: person[0].id, sfzh: person[0].sfzh, xm: person[0].xm, disabled: true })
                } else {
                  this.xyrAll.push({ id: person[0].id, sfzh: person[0].sfzh, xm: person[0].xm, disabled: false })
                }
              })
              // response.data.result.gkqkList.filter(item => !item.ysscqsId).map(item => { return { id: item.id, sfzh: item.sfzh, xm: item.xm } }).forEach(
              //   item => {
              //     if (!this.xyrAll.find(it => it.sfzh === item.sfzh)) {
              //       this.xyrAll.push(item)
              //     }
              //   }
              // )
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.xyrAll = []
        })
      }
    },
    detail(id) {
      this.subtimestamp = new Date().getTime()
      this.postForm.id = id
      this.subReadOnly = true
      this.dialogtitle = '查看'
      this.dialogVisible = true
      this.getYsscqsById(id)
    },
    edit(id) {
      this.subtimestamp = new Date().getTime()
      this.postForm.id = id
      this.subReadOnly = false
      this.dialogtitle = '修改'
      this.dialogVisible = true
      this.getYsscqsById(id)
    },
    addnew() {
      this.subtimestamp = new Date().getTime()
      this.postForm = Object.assign({}, defaultForm)
      this.xfrList = []
      this.postForm.id = 0
      this.subReadOnly = false
      this.dialogtitle = '新增'
      this.dialogVisible = true
    },
    getYsscqsById(id) {
      this.$http
        .get('/api/busWw/getById?&id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.postForm = response.data.result
            // if (this.postForm.xfrList && this.postForm.xfrList.length > 0) {
            this.xfrList = this.postForm.xfrList
            // }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.infoLoading = false
        })
    },
    canEdit(zt) {
      if (this.unitName === '政法委' && this.roleName === '录入') {
        if (zt === 1 || zt === 2) {
          return false
        } else {
          return true
        }
      } else {
        return false
      }
    },
    indexMethod(index) {
      index = (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit
      return index
    },
    showSupervise() {
      return true
      // return JSON.parse(localStorage.getItem('user')).unitName === '处非办' || JSON.parse(localStorage.getItem('user')).unitName === '政法委' || JSON.parse(localStorage.getItem('user')).unitName === '督查室' || JSON.parse(localStorage.getItem('user')).unitName === '政法委'
    },
    updateFj(list) {
      this.fjList = list
    },
    dateFormat(date) {
      console.log('日期转换')
      console.log(date)
      return date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString() + '-' + date.getDate().toString()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const fid = file.id
      this.$http.get('api/gen/file/remove?id=' + fid).then(res => {
        if (res.data.success === true) {
          this.fileList = this.fileList.filter(item => item.id !== fid)
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
        }
      })
    },
    handleDeleteFile(index) {
      this.fjList.splice(index, 1)
    },
    submitFileForm() {
      if (this.fileList && this.fileList.length > 0) {
        console.log(this.fileList)
        this.fileList[0].remark = this.filePostForm.remark
        this.filePostForm = Object.assign({}, defaultFileForm)
        if (this.fjindex === -1) {
          this.fjList.push(this.fileList[0])
        } else {
          this.fjList[this.fjindex] = this.fileList[0]
          this.fjindex = -1
        }
        this.fileList = []
        this.fileDialogVisible = false
      } else {
        this.$message({
          message: '请上传文件',
          type: 'error'
        })
      }
    },
    editFile(index, item) {
      this.fileList = []
      this.fileList.push(item)
      this.filePostForm.remark = item.remark
      this.filePostForm.dataCreateDatetime = item.dataCreateDatetime
      this.fjindex = index
      this.fileDialogVisible = true
      this.fileDialogTitle = '修改'
    },
    addFile() {
      this.filePostFormForm = Object.assign({}, defaultFileForm)
      this.fileDialogVisible = true
      this.fileDialogTitle = '新增'
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    getFj(id) {
      const para = {
        pageNum: 1,
        pageSize: 1000,
        cfajbh: id,
        businessTable: 'bus_ysscqs'
      }
      this.fjloading = true
      this.$http
        .post('/api/gen/file/search', para)
        .then(response => {
          this.loading = false
          if (response.data.success === true) {
            this.fjList = response.data.result.records.map(item => { return { name: item.fileName + '.' + item.fileType, remark: item.remark, id: item.id, dataCreateDatetime: item.dataCreateDatetime } })
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function(error) {
          console.log(error)
          this.fjloading = false
        })
    },
    getData() {
      if (this.cfajbh) {
        const para = {
          id: this.postForm.id,
          cfajbh: this.cfajbh,
          orderField: this.Sortkey,
          orderType: this.Isace,
          pageNum: this.listQuery.page,
          pageSize: this.listQuery.limit
        }
        this.listLoading = true
        this.$http
          .post('/api/busWw/queryByPage', para)
          .then(response => {
            this.listLoading = false
            if (response.data.success === true) {
              this.list = response.data.result.records
              this.total = response.data.result.total
              if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
                this.listQuery.page = response.data.result.pages
                this.getData()
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.listLoading = false
          })
      }
    },
    sortChange(column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getData()
    },
    submitForm(flag) {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          const para = {
            id: this.postForm.id ? this.postForm.id : null,
            cfajbh: this.cfajbh,
            xfsj: this.postForm.xfsj,
            zrdw: this.postForm.zrdw,
            zrld: this.postForm.zrld,
            zrlddh: this.postForm.zrlddh,
            jtzrr: this.postForm.jtzrr,
            zrrdh: this.postForm.zrrdh,
            xflb: this.postForm.xflb,
            jjfsdslqfqk: this.postForm.jjfsdslqfqk,
            zysq: this.postForm.zysq,
            dfnr: this.postForm.dfnr,
            xyrIds: this.xyrlist,
            files: this.fjList.map(item => { return { fileId: item.id, remark: item.remark, classCode: item.classCode } }),
            shzt: flag,
            xfrList: this.xfrList
          }
          this.loading = true
          this.$http
            .post('/api/busWw/save', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.postForm = Object.assign({}, defaultForm)
                this.xyrlist = []
                this.xyrAll = []
                this.loading = false
                this.getXyrAll()
                this.getData(this.cfajbh)
              } else {
                console.log('保存失败:' + response.data.message)
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
